<template>
	<view>
		<view class="history-list">
			<view class="history-item" v-for="(item, index) in weightHistory" :key="index" v-if="index<=4">
				<view class="date">{{$u.timeFormat((new Date(item.date).getTime()), 'yyyy年mm月dd日 hh:MM:ss')}}</view>
				<view class="weight">{{item.weight}}kg</view>
				<view class="change" :class="item.change >= 0 ? 'up' : 'down'">
					{{item.change >= 0 ? '+' : ''}}{{item.change}}kg
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				weightHistory: [],
			};
		},
		methods:{
			async loadData() {
				try {
					// 获取体重历史记录
					const {
						result: historyResult
					} = await uniCloud.callFunction({
						name: 'weight',
						data: {
							action: 'getList',
							token: uni.getStorageSync('jfToken')
						}
					})
			
					if (historyResult.code === 0) {
						this.weightHistory = historyResult.data.map((item, index) => {
							const prevWeight = index < historyResult.data.length - 1 ? historyResult.data[
								index + 1].weight : item.weight
							return {
								...item,
								change: (item.weight - prevWeight).toFixed(1)
							}
						})
					}
				} catch (e) {
					uni.showToast({
						title: '加载数据失败',
						icon: 'none'
					})
				}
			},
		},
		onLoad() {
			this.loadData()
		}
	}
</script>

<style lang="scss">
	.history-list {
		padding: 30rpx;
		.history-item {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx 0;
			border-bottom: 1rpx solid #f0f0f0;

			&:last-child {
				border-bottom: none;
			}

			.date {
				font-size: 24rpx;
				color: #666;
			}

			.weight {
				font-size: 28rpx;
				font-weight: bold;
			}

			.change {
				font-size: 24rpx;

				&.up {
					color: red;
				}

				&.down {
					color: green;
				}
			}
		}
	}
</style>